#define _CRT_SECURE_NO_WARNINGS 1

//https://leetcode.cn/problems/01-matrix/

class Solution {
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    vector<vector<int>> dist;
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        int m = mat.size(), n = mat[0].size();
        queue<pair<int, int>> q;
        dist.resize(m, vector<int>(n));
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
            {
                if (mat[i][j] == 0)
                {
                    q.push({ i,j });
                    dist[i][j] = 0;
                }
                else dist[i][j] = -1;
            }

        while (q.size())
        {
            auto [a, b] = q.front();
            q.pop();

            for (int z = 0; z < 4; z++)
            {
                int x = a + dx[z], y = b + dy[z];
                if (x >= 0 && x < m && y >= 0 && y < n && dist[x][y] == -1)
                {
                    dist[x][y] = dist[a][b] + 1;
                    q.push({ x,y });
                }
            }
        }
        return dist;
    }
};